<script lang="ts" setup>
//TODO
import {computed, onMounted, ref} from 'vue'
import {useBrowsingHistoryStore} from "@/stores/browsingHistory"
import {onPullDownRefresh, onReachBottom} from "@dcloudio/uni-app";
import {deleteUserFavApi, getUserFavApi} from "@/api/user";
import type {CollectionItem} from "@/types/user";
import {formatDate_1} from "@/utils/time";
import {useUserStore} from "@/stores/user";

const {safeAreaInsets, windowWidth} = uni.getSystemInfoSync()


const userStore = useUserStore()
const browsingHistoryStore = useBrowsingHistoryStore()
onPullDownRefresh(() => {
  setTimeout(() => {
    uni.stopPullDownRefresh()
  }, 300)

})
const userFavList = ref<CollectionItem[]>([])
/**
 * 获取用户收藏
 */
let page: number = 1
let pageSize: number = 15
let isNoMore: boolean = false
let delay: boolean = false
let type = ref<0 | 1>(0)
const getUserFav = async () => {
  if (delay) {
    return
  }
  delay = true
  const res = await getUserFavApi(page, pageSize, type.value)
  console.log(res)
  delay = false
  if (res.data.total <= pageSize * page) {
    isNoMore = true
  }
  if (!isNoMore && res.data.data !== null) {
    userFavList.value = [...res.data.data, ...userFavList.value]
  } else {
    userFavList.value = res.data.data
  }
  checkList.value = new Array(userFavList.value?.length).fill(false)
}

const checkedNum = computed(() => {
  return checkList.value.filter(item => item).length
})
onReachBottom(() => {
  if (isNoMore) {
    return
  }
  // 触底加载
  page++
  getUserFav()
})
onMounted(() => {
  getUserFav()
  uni.startPullDownRefresh()
})


const checkList = ref<boolean[]>([])
const isShowCheck = ref(false)
// 计算是否全选
const isCheckedAll = computed(() => {
  return checkList.value?.every(item => item)
})
/**
 * 长按
 * @param index 长按目标
 */
const onLongPress = (index: number) => {
  isShowCheck.value = !isShowCheck.value
  checkList.value![index] = true
}

//删除
const fPopup = ref()
const onDeleteHistory = () => {
  // 检查是否至少有一个被勾选了
  if (checkList.value?.every(item => !item)) {
    return uni.showToast({title: "请选择要移除的收藏", icon: "none"})
  }
  fPopup.value.open()
}
/**
 * 确认移除
 */
const onConfirmDelete = async () => {
  const ids = checkList.value?.map((item, index) => {
    if (item) {
      return userFavList.value[index].favId
    }
  })
  if (ids?.length === 0) {
    return
  }
  const res = await deleteUserFavApi(ids as string[])
  if (res.code !== '1') {
    return uni.showToast({title: "服务器繁忙，请稍后重试", icon: "none"})
  }
  isShowCheck.value = false
  userFavList.value = []
  page = 1
  await getUserFav()
}

/**
 * 点击图片
 * @param id 动物id
 * @param type
 * @param cover
 * @param creator
 */
const onClickImg = (id: string, type: 0 | 1, creator: number, cover?: string) => {
  if (type === 0) {
    if (cover=== null) {
      return uni.showToast({title: "该图文已被删除了哟~", icon: "none"})
    }
    return uni.navigateTo({url: `/subPkg/detail/detail?id=${id}`})
  } else if (type === 1) {
    if (creator === null) {
      return uni.showToast({title: "该图集已被删除了哟~", icon: "none"})
    }
    return uni.getImageInfo({
      src: cover!,
      success: (res) => {
        const height = windowWidth / res.width * res.height
        uni.navigateTo({
          url: '/subPkg/picDetail/picDetail?id=' + id + '&cover=' + cover + '&height=' + height
        })
      },
      fail: (e) => {
        uni.navigateTo({
          url: '/subPkg/picDetail/picDetail?id=' + id + '&cover=' + cover
        })
      }
    })
  }
}
/**
 * 点击右侧区域
 * @param id
 * @param index
 * @param type
 * @param creator
 * @param cover
 */
const onClickRight = (id: string, index: number, type: 0 | 1, creator: number, cover?: string) => {
  if (!isShowCheck.value) {
    if (type === 0) {
      if (cover === null) {
        return uni.showToast({title: "该图文已被删除了哟~", icon: "none"})
      }
      return uni.navigateTo({url: `/subPkg/detail/detail?id=${id}`})
    } else if (type === 1) {
      console.log(111)
      if (creator === null) {
        return uni.showToast({title: "该图集已被删除了哟~", icon: "none"})
      }
      return uni.getImageInfo({
        src: cover!,
        success: (res) => {
          const height = windowWidth / res.width * res.height
          uni.navigateTo({
            url: '/subPkg/picDetail/picDetail?id=' + id + '&cover=' + cover + '&height=' + height
          })
        },
        fail: (e) => {
          uni.navigateTo({
            url: '/subPkg/picDetail/picDetail?id=' + id + '&cover=' + cover
          })
        }
      })
    }

  }
  checkList.value![index] = !checkList.value![index]
}

/**
 * TODO
 * @param value 过滤词
 */
const onFilterHistory = (value: string) => {
  uni.showToast({title: "这个功能以后再用吧ヾ(≧▽≦*)o", icon: "none"})
}
/**
 * 点击更多
 */
const onClickMore = (id: string) => {
  uni.showActionSheet({
    itemList: ['移除该收藏'],
    itemColor: '#39c5bb',
    success: async function (res) {
      if (res.tapIndex === 0) {
        await deleteUserFavApi([id])
        uni.showToast({title: '已移除', icon: 'none'})
        await getUserFav()
      }
    },
    fail: function (res) {
    }
  });
}
const list = [{
  name: '图文'
}, {
  name: '图集',
}]

interface tabChange {
  index: 0 | 1
  name: string
}

let timer: number
const currentIndex = ref(0)
const onChange = (e: tabChange) => {
  userFavList.value = []
  type.value = e.index
  currentIndex.value = e.index
  isNoMore = false
  uni.startPullDownRefresh()
  getUserFav()
}

const isEmpty = computed(() => {
  return !userFavList.value
})
</script>

<template>

  <view>
    <view style="position:fixed;top: 0;left: 0;right: 0;z-index: 999;">
      <aw-nav-second :title="'我的收藏'"></aw-nav-second>
    </view>
    <!--   顶部nav -->
    <view :style="{paddingTop:safeAreaInsets?.top+50+'px'}" style="width: 100%;height: 30px">
      <uv-tabs :activeStyle="{
			color: '#303133',
			fontWeight: 'bold',
			transform: 'scale(1.08)'
    	}" :inactiveStyle="{
			color: '#606266',
			transform: 'scale(1)'
		}"
               :lineColor="'#39c5bb'"
               :list="list"
               itemStyle="padding-left: 15px; padding-right: 15px; height: 42px;"
               lineWidth="30"
               @click="onChange"></uv-tabs>
    </view>
    <!--  空状态  -->
    <view v-if="isEmpty" class="flex justify-center align-center flex-column"
          style="width: 100%;height: 70vh">
      <uv-empty :text="'这里什么都没有哟ヾ(≧▽≦*)o'"></uv-empty>
    </view>

    <!--  数据列表  -->
    <view :scroll-y="true" class="history-list">
      <view v-for="(item, index) in userFavList" :key="index" class=" history-item" style="position: relative"
            @longpress="onLongPress(index)">
        <view v-show="isShowCheck" :class="{ 'cuIcon-check': checkList[index], 'bg-gradual-awGreen': checkList[index] }"
              :style="{ border: !checkList[index] ? '#aaaaaa 1px solid' : 'none' }"
              class="round margin-lr-sm flex justify-center align-center"
              style="width: 52rpx;height: 52rpx;font-size: 40rpx;border: #aaaaaa 1px solid"
              @click="checkList[index] = !checkList[index]">
        </view>

        <view class="left">
          <uv-image :src="item.img" height="100%" mode="aspectFill" radius="10" width="100%"
                    @click="onClickImg(item.id,item.type,item.creatorId,item.img)">
            <template v-slot:loading>
              <view class="flex flex-column justify-center align-center padding-bottom-sm"
                    style="width: 100%;height: 100%;overflow: hidden">
                <uv-image :src="'/static/home-selected.png'" height="100%" mode="aspectFit" width="100%"></uv-image>
                <text v-if="!item.img" class="text-gray text-sm flex justify-center align-center " style="">图片暂缺
                </text>
              </view>
            </template>
            <template v-slot:error>
              <view class="flex flex-column justify-center align-center padding-bottom-sm bg-white"
                    style="width: 100%;height: 100%;overflow: hidden">
                <uv-image :src="'/static/error-img.png'" height="100%" mode="aspectFit" width="100%"></uv-image>
              </view>
            </template>
          </uv-image>
        </view>

        <view class="right padding-sm flex flex-column justify-between"
              @click="onClickRight(item.id, index,item.type,item.creatorId,item.img)">
          <text v-if="type===0" class="text-black">{{ item.name }}</text>
          <text v-else class="text-black">
            <text v-show="item.creatorId" class="text-gray">来自：</text>
            {{
              item.creatorId ? userStore.userInfoData?.userID === item.creatorId ? '我自己'
                      : item.creatorName
                  : item.desc
            }}
          </text>
          <text v-show="type!==1" class="text-gray basis-xl" style="text-overflow: ellipsis;line-clamp: 2">{{
              item.desc?.substring(0, 30)
            }}
          </text>
          <text class="text-gray text-sm" style="justify-self: flex-end">
            {{ formatDate_1(Date.parse(userFavList[index]?.updateTime)) }}
          </text>
          <text class="cuIcon-moreandroid text-xs text-gray"
                style="position: absolute;right: 10rpx;bottom: 20rpx;font-size: large"
                @click.stop="onClickMore(item.favId)"></text>
        </view>
      </view>


      <view v-if="userFavList?.length" class="flex justify-center text-gray padding-sm" style="width: 100%">
        已经到底了哟~
      </view>
    </view>

    <!--   全部删除 -->
    <view v-show="isShowCheck" class="cu-bar bg-white tabbar border shop" style="position: fixed;bottom:0;width: 100%;">
      <view class="flex justify-start align-center">
        <view :class="{ 'cuIcon-check': isCheckedAll, 'bg-gradual-awGreen': isCheckedAll }"
              :style="{ border: !isCheckedAll ? '#aaaaaa 1px solid' : 'none' }"
              class="round margin-lr-sm flex justify-center align-center"
              style="width: 52rpx;height: 52rpx;font-size: 40rpx" @click="checkList?.fill(!isCheckedAll)">
        </view>
        <text class="text-lg text-gray margin-left-sx">全选
          <text class="text-sm">共
            <text class="text-awGreen">{{ userFavList?.length }}</text>
            条
          </text>
          |
          <text class="text-sm">已选
            <text class="text-awGreen">{{ checkedNum }}</text>
            条
          </text>
        </text>
      </view>
      <view class="action" style="width: auto">
        <text class="text-lg text-awGreen margin-right-xl" @click="onDeleteHistory">
          {{ isCheckedAll ? '移除全部' : '移除选中' }}
        </text>
      </view>
    </view>

  </view>

  <!--  弹出层-->
  <uni-popup ref="fPopup" type="center">
    <uni-popup-dialog :confirm-text="isCheckedAll ? '全部移除' : '移除选中'" content="确定要移除该收藏吗？" title="提示"
                      type="info"
                      @confirm="onConfirmDelete">
    </uni-popup-dialog>
  </uni-popup>
</template>


<style lang="scss">
page{
  background-color: #fff;
}
/* #ifdef H5 */
body {
  background-color: #f1f1f1;
}

/* #endif */
.nav {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 0 30rpx;
  height: 100rpx;
  font-size: 32rpx;
  color: #333;
  border-bottom: #8d8d8d 1rpx solid;
}

.history-list {
  padding:40px 0 20rpx 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  /* #ifdef H5 */
  padding-top: 40px;
  /* #endif */
}

.history-item {
  width: 100%;
  height: 200rpx;
  //border-radius: 20rpx;
  margin: 10rpx;
  display: flex;
  justify-content: flex-start;
  border-bottom: #cccccc 1px solid;
  padding-bottom: 5px;
  align-items: center;
  background: #FFFFFF;
  //box-shadow: rgba(0, 0, 0, 0.1) 0px 4px 12px;

  .left {
    flex: 3;
    height: 100%;
    border-radius: 20rpx;
  }

  .right {
    flex: 5;
    height: 100%;;
  }

}
</style>